<?php

namespace App\Models\Shop;

use Illuminate\Database\Eloquent\Model;
use Tymon\JWTAuth\Facades\JWTAuth;

class Cart extends Model
{
   protected $fillable = ['product_id', 'user_id', 'num'];

   //购物车属于商品
   public function product()
   {
      return $this->belongsTo(Product::class, 'product_id');
   }

   //计算购物车总价和数量
   static function count_cart($carts = null)
   {
//      $user = JWTAuth::parseToken()->authenticate();  //取其id为$user->id

      $count = [];
      //避免重复查询
      $carts = $carts ? $carts : Cart::with('product')->where('user_id', 1)->get();

      $total_price = 0;
      $num = 0;
      foreach ($carts as $v) {
         $total_price += $v->product->price * $v->num;
         $num += $v->num;
      }
      $count['total_price'] = $total_price;
      $count['num'] = $num;

      return $count;
   }

   //获取购物车的商品和数量价格统计
   static function all_carts()
   {
//      $user = JWTAuth::parseToken()->authenticate();  //取其id为$user->id
      $carts = self::with('product')->where('user_id', 1)->get();
      $product_num = self::count_cart();

      return compact('carts', 'product_num');
   }

}
